package com.wct.spzx.manager.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSON;
import com.wct.spzx.common.exception.LoginErrorException;
import com.wct.spzx.manager.mapper.SysUserMapper;
import com.wct.spzx.manager.service.SysUserService;
import com.wct.spzx.model.dto.system.LoginDto;
import com.wct.spzx.model.entity.system.SysUser;
import com.wct.spzx.model.entity.user.UserInfo;
import com.wct.spzx.model.vo.common.ResultCodeEnum;
import com.wct.spzx.model.vo.system.LoginVo;
import jakarta.annotation.Resource;
import lombok.extern.java.Log;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author Administrator
 */
@Log
@Service
public class SysUserServiceImpl implements SysUserService {
    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public LoginVo login(LoginDto loginDto) {

        //1 提交的验证码是否正确
        String redisValidateCode = redisTemplate.opsForValue().get(loginDto.getCodeKey());
        if (!loginDto.getCaptcha().equals(redisValidateCode)) {
            throw new LoginErrorException(ResultCodeEnum.VALIDATECODE_ERROR);
        }

        //2 根据用户名查询用户是否存在
        SysUser sysUser = sysUserMapper.selectUserInfoByUserName(loginDto.getUserName());
        if (sysUser == null) {
            throw new LoginErrorException(ResultCodeEnum.LOGIN_ERROR);
        }

        //3 验证密码是否正确
        String inputPassword = loginDto.getPassword();
        String md5InputPassword = DigestUtils.md5DigestAsHex(inputPassword.getBytes());
        if (!md5InputPassword.equals(sysUser.getPassword())) {
//            throw new RuntimeException("用户名或者密码错误2");
            throw new LoginErrorException(ResultCodeEnum.LOGIN_ERROR);
        }

        StpUtil.login(sysUser.getId());
        //4 生成令牌，保存数据到Redis中
        String token = StpUtil.getTokenValue();
//        String token = UUID.randomUUID().toString().replace("-", "");

        //5 保存用户登录信息到Redis中
        redisTemplate.opsForValue().set(
                "user:login:" + token,
                JSON.toJSONString(sysUser),
                5,
                TimeUnit.MINUTES);

        //6 删除redis中的验证码
        redisTemplate.delete(loginDto.getCodeKey());

        //7 构建响应结果对象
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setRefresh_token("");

        //8 返回
        return loginVo;
    }

    @Override
    public UserInfo getUserInfo(String token) {
        String userJson = redisTemplate.opsForValue().get("user:login:" + token);
        return JSON.parseObject(userJson, UserInfo.class);
    }

    @Override
    public void logout(String token) {
        String userJson = redisTemplate.opsForValue().get("user:login:" + token);
        UserInfo userInfo = JSON.parseObject(userJson, UserInfo.class);
        redisTemplate.delete("user:login:" + token);
        if (userInfo!= null) {
            StpUtil.logout(userInfo.getId());
        }
    }
}
